package com.example.targetOffer.service.impl;

import com.example.targetOffer.service.LinkedListService;
import com.example.targetOffer.struct.ListNode;
import org.springframework.stereotype.Service;

@Service
public class LinkedListServiceImpl implements LinkedListService {

    /**
     * @param head
     * @return
     * @describe: 【倒序输出 >> 法1：借用栈的特性。 法2: 借用数组的倒序输出。
     */
    @Override
    public int[] reversePrint(ListNode head) {
        if (head == null) return new int[0];
        int j = getNodeLength(head);
        ListNode node = head;
        int[] array = new int[j];
        while (j != 0) {
            array[--j] = node.val;
            node = node.next;
        }
        return array;
    }

    private int getNodeLength(ListNode node) {
        int j = 0;
        while (node != null) {
            j++;
            node = node.next;
        }
        return j;
    }
}
